<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Session;
use App\Models\Users;
use App\Models\Usersinvitations;
use App\Models\Usersauthority;
use App\Services\CommonService;
use App\Services\OutputService;
use App\Services\WechatoffiaccountService;
use App\Services\WechatOpenidService;
use App\Services\CalltaskService;
use App\Services\WorkcustomService;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redis;
use EasyWeChat\Factory;
use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;
use GuzzleHttp\Client;
use Auth,Exception,Log,Response,Config;
use Carbon\Carbon;

class LoginController extends Controller
{
    public function login(Request $request)
    {
        return view('admin.login.login');
    }

    public function loginSubmit(Request $request)
    {
        if (empty($request->username) || empty($request->password)) return back()->with("status","error")->with("msg","账号或者密码为空！")->withInput();
        $username = str_replace(" ","",$request->username);
        //校验是否存在
        $users = Users::getAdminByUsername($username);
        //没有命中，返回错误提示
        if (empty($users)) {
            $password = Hash::make($request->password);
            $users_id = Users::adminAdd($username,$password,"默认昵称",1);
        } else {
            //账号已被禁用
            if ($users->disable == 2) return back()->with("status","error")->with("msg","对不起，此账号已被禁用")->withInput();
            if (empty($users->password)) {
                $password = Hash::make($request->password);
                Users::phoneBind($users->id,$users->username,$password);
            } else {
                if (!password_verify($request->password,$users->password)) return back()->with("status","error")->with("msg","您输入的密码错误！")->withInput();
            }
            $users_id = $users->id;
        }
        // 验证成功，加入auth
        Auth::loginUsingId($users_id,true);
        return redirect("/admin/users/users_center");
    }

    public function loginToken(Request $request)
    {
        if(empty($request->token)) return view("links.notice",["msg"=>"参数错误!"]);
        try {
            $users_id = decrypt($request->token);
            Auth::loginUsingId($users_id,true);
            return redirect("/app");
        } catch (Exception $e) {
            return view("links.notice",["msg"=>"参数错误!"]);
        }
    }

    public function loginCheck(Request $request)
    {
        if(empty($request->token)) return Response::json(["status"=>"error","code"=>"1001","msg"=>"Token错误,请稍后访问"]);
        if(empty($request->time)) return Response::json(["status"=>"error","code"=>"1002","msg"=>"Time错误,请稍后访问"]);
        if(empty($request->sign)) return Response::json(["status"=>"error","code"=>"1003","msg"=>"Sign错误,请稍后访问"]);

        $token = $request->token;
        $time = $request->time;
        $sign = $request->sign;
        $code = $request->code;
        $keyword = urldecode($request->keyword);
        if (strpos($keyword, '%E') !== false) {
            $keyword = urldecode($keyword);
        }
        $newsign = md5($token.$time.$token."sign");
        if ($newsign != $sign) return Response::json(["status"=>"error","code"=>"1003","msg"=>"签名错误,请稍后访问！"]);
        try {
            $userInfo = Users::getAdminByToken($token);
        } catch (Exception $e) {
            return Response::json(["status"=>"error","code"=>"1003","msg"=>"查询错误,请稍后访问！"]);
        }
        if (empty($userInfo)) return Response::json(["status"=>"error","code"=>"1003","msg"=>"未查询到公众号关注,请微信扫码关注后重试！"]);
        // 账号已被禁用
        if ($userInfo->disable == 2) return Response::json(["status"=>"error","code"=>"1004","msg"=>"对不起，此账号已被禁用！"]);
        // 获取邀请人
        $difftime = (new Carbon)->diffInSeconds($userInfo->created_at, true); 
        if ($difftime <= 300) {
            // 获取邀请人
            if (!empty($code)) {
                $users_invitation_id = CommonService::aesDncrypt(urldecode($code));
                if(empty($users_invitation_id)){
                    $code = mb_strlen($code) > 20 ? mb_substr($code, 0,20) : $code;
                    $keyword = mb_strlen($keyword) > 20 ? mb_substr($keyword, 0,20) : $keyword;
                    try {
                        Users::updateKeyword($userInfo->id,$code,$keyword,$request->device);
                    } catch (Exception $e) {
                        Users::updateKeyword($userInfo->id,$code,1,$request->device);
                    }
                }else{
                    Usersinvitations::addUsersInvitation($userInfo->id,$users_invitation_id);
                    $ncode = mb_strlen($request->ncode) > 20 ? mb_substr($request->ncode, 0,20) : $request->ncode;
                    try {
                        Users::updateKeyword($userInfo->id,$ncode,$keyword,$request->device);
                    } catch (Exception $e) {
                        Users::updateKeyword($userInfo->id,$ncode,1,$request->device);
                    }
                }
            }else{
                if (!empty($request->ncode) || !empty($keyword)){
                    $ncode = mb_strlen($request->ncode) > 20 ? mb_substr($request->ncode, 0,20) : $request->ncode;
                    $keyword = mb_strlen($keyword) > 20 ? mb_substr($keyword, 0,20) : $keyword;
                    try {
                        Users::updateKeyword($userInfo->id,$ncode,$keyword,$request->device);
                    } catch (Exception $e) {
                        Users::updateKeyword($userInfo->id,$ncode,1,$request->device);
                    }
                }
            }
        }
        // 清空登录Token
        Users::emptyUsersToken($userInfo->id);
        if(empty($userInfo->username) && !empty($request->username)){
            $usersphone = Users::getAdminByUsername($request->username);
            if(empty($usersphone)){
                Users::phoneBind($userInfo->id,$request->username,'');
                Auth::loginUsingId($userInfo->id,true);
                //新注册用户，加入拨打电话任务
                CalltaskService::phonePush($request->username);
                $username = $request->username;
            }else{
                if(empty($usersphone->unionid)){
                    //绑定到手机号上并删除原来的公众号登录信息
                    Users::bindScanUnionidByUserName($request->username,$userInfo->unionid,$userInfo->wechat_openid);
                    Users::deleteUser($userInfo->id);
                    Auth::loginUsingId($usersphone->id,true);
                }
                Auth::loginUsingId($usersphone->id,true);
                $username = $usersphone->username;
            }
        }elseif(empty($userInfo->username) && empty($request->username)){
            $username = $userInfo->username;
        }
        else{
            Auth::loginUsingId($userInfo->id,true);
            $username = $userInfo->username;
        }
        $unionid = empty($userInfo->unionid) ? "" : $userInfo->unionid;
        if(time() - strtotime($userInfo->created_at) > 259200){
            $jump = '/admin/links_lists/lists';
        }else{
            $jump = '/admin/links_lists/links_lists_add';
        }
        return Response::json(["status"=>"success","code"=>"1000","msg"=>"登录成功！","username"=>$username,"unionid"=>$unionid,"jump"=>$jump]);
    }

    public function captchaImage(Request $request)
    {
        //生成验证码图片的Builder对象，配置相应属性
        $phraseBuilder = new PhraseBuilder(4,'0123456789');
        $builder = new CaptchaBuilder(null ,$phraseBuilder);
        // 设置背景颜色
        $builder->setBackgroundColor(220, 210, 230);
        $builder->setMaxAngle(25);
        $builder->setMaxBehindLines(0);
        $builder->setMaxFrontLines(0);
        //可以设置图片宽高及字体
        $builder->build($width = 100, $height = 37, $font = null);
        //获取验证码的内容,并转化为小写
        $phrase = strtolower($builder->getPhrase());
        //把内容存入session
        Session::put('phrase', $phrase);
        //生成图片
        header("Cache-Control: no-cache, must-revalidate");
        header('Content-Type: image/jpeg');
        $builder->output();
    }

    public function register(Request $request)
    {
        $config = Config::get("wechat_login.setting");
        $app = Factory::officialAccount($config);
        $redirectUrl = $app->oauth->scopes(['snsapi_login'])->redirect($request->url()."_back");
        return redirect($redirectUrl);
    }

    public function registerSubmit(Request $request)
    {
        $config = Config::get("wechat_login.setting");
        try {
            $app = Factory::officialAccount($config);
            $user = $app->oauth->userFromCode($request->code);
            $getOriginal = $user->getRaw();
        } catch (Exception $e) {
            $message = $e->getMessage();
            return redirect("/admin/login");
        }

        if (empty($user->getId())) return back()->with("status","error")->with("msg","登录失败,请重新登录！")->withInput();
        // $users = Users::getUsersByWebOpenid($getOriginal["openid"]);
        $users = Users::getUsersByUnionid($getOriginal["unionid"]);
        $address = $getOriginal["country"].$getOriginal["province"].$getOriginal["city"];

        if (empty($users)) {
            // 创建用户
            $users_id = Users::creatUsersByWebOpenid($getOriginal["openid"],$getOriginal["headimgurl"],$getOriginal["nickname"],$getOriginal["sex"],$address,$getOriginal["unionid"]);
            Usersauthority::createUsersAuthority($users_id,1,1);
            $code = session('code');
            // 获取邀请人
            if (!empty($code)) {
                $users_invitation_id = CommonService::aesDncrypt($code);
                Usersinvitations::addUsersInvitation($users_id,$users_invitation_id);
            }
        } else {
            //账号已被禁用
            if ($users->disable == 2) return redirect("/admin/login")->with("status","error")->with("msg","对不起，此账号已被禁用!");
            // if ($getOriginal["nickname"] != $users->nike) {
            // 更新用户信息
            Users::updateUsersByWebOpenid($users->id,$getOriginal["openid"],$getOriginal["headimgurl"],$getOriginal["nickname"],$getOriginal["sex"],$address,$getOriginal["unionid"]);
            // }
            $users_id = $users->id;
        }

        // 验证成功，加入auth
        Auth::loginUsingId($users_id);
        return redirect("/admin/links_lists/links_lists_add");
    }

    public function loginOut(Request $request)
    {
        Auth::logout();
        return redirect("/admin/login");
    }

    public function phoneBind(Request $request)
    {
        if (Auth::check()) {
            $unionid = Auth::user()->unionid;
            $username = Auth::user()->username;
            if(!empty($username)) return redirect("/admin/links_lists/links_lists_add");
            $time = time();
            $sign = CommonService::aesEncrypt($unionid.$time);
            return view('admin.login.phone_bind',["unionid"=>$unionid,"time"=>$time,"sign"=>$sign]);
        } else {
            return redirect("/admin/login");
        }
    }

    public function phoneBindSubmit(Request $request)
    {
        if (!Auth::check()) return redirect("/admin/login");
        if(empty($request->phone)) return back()->with("status","error")->with("msg","请输入手机号码！")->withInput();
        if(empty($request->msncode)) return back()->with("status","error")->with("msg","请输入手机验证码！")->withInput();
        if(empty($request->password)) return back()->with("status","error")->with("msg","请输入密码！")->withInput();
        if(mb_strlen($request->password) <= 5) return back()->with("status","error")->with("msg","密码不得少于6位！")->withInput();
        $msncode = Redis::get("register".$request->phone);
        if (empty($msncode)) return back()->with("status","error")->with("msg","短信验证码已过期,请重新获取！")->withInput();
        $msninfo = json_decode($msncode);
        if ($msninfo->code != $request->msncode) return back()->with("status","error")->with("msg","短信验证码错误,请重新填写验证码！")->withInput();
        $existusername = Users::getAdminByUsername($request->phone);
        if (!empty($existusername)) {
            if ($existusername->id != Auth::user()->id) return back()->with("status","error")->with("msg","电话号码已被其他账户绑定！")->withInput();
        }
        $password = Hash::make($request->password);
        Users::phoneBind(Auth::user()->id,$request->phone,$password);
        return redirect("/admin/links_lists/links_lists_add");
    }

    public function phoneReigster(Request $request)
    {
        return redirect("/admin/login")->with("status","error")->with("msg","请使用扫码登录!");
        $unionid = md5(time().rand(1000,9999));
        $time = time();
        $sign = CommonService::aesEncrypt($unionid.$time);
        return view('admin.login.phone_register',["unionid"=>$unionid,"time"=>$time,"sign"=>$sign]);
    }

    public function phoneReigsterSubmit(Request $request)
    {
        return redirect("/admin/login")->with("status","error")->with("msg","请使用扫码登录!");
        if(empty($request->phone)) return back()->with("status","error")->with("msg","请输入手机号码！")->withInput();
        if(empty($request->msncode)) return back()->with("status","error")->with("msg","请输入手机验证码！")->withInput();
        if(empty($request->password)) return back()->with("status","error")->with("msg","请输入密码！")->withInput();
        if(mb_strlen($request->password) <= 5) return back()->with("status","error")->with("msg","密码不得少于6位！")->withInput();
        $msncode = Redis::get("register".$request->phone);
        if (empty($msncode)) return back()->with("status","error")->with("msg","短信验证码已过期,请重新获取！")->withInput();
        $msninfo = json_decode($msncode);
        if ($msninfo->code != $request->msncode) return back()->with("status","error")->with("msg","短信验证码错误,请重新填写验证码！")->withInput();
        $existusername = Users::getAdminByUsername($request->phone);
        if (!empty($existusername)) return back()->with("status","error")->with("msg","该账号已注册,请直接前往登录!")->withInput();
        $password = Hash::make($request->password);
        $users_id = Users::phoneRegister($request->phone,$password);
        Auth::loginUsingId($users_id,true);
        return redirect("/admin/links_lists/links_lists_add");
    }

    public function submitLogin(Request $request)
    {
        if ($request->token != md5($request->username."S".$request->phone."A".$request->timestamp)) return OutputService::error("接口异常,请稍后重试！");
        if ($request->login_type == "phone") {
            if(empty($request->phone)) return OutputService::error("请输入手机号码！");
            if(empty($request->msncode)) return OutputService::error("请输入短信验证码！");
            $phone = str_replace(" ","",$request->phone);
            $msncode = Redis::get("register".$phone);
            if (empty($msncode)) return OutputService::error("短信验证码已过期,请重新获取！");
            $msninfo = json_decode($msncode);
            if ($msninfo->code != $request->msncode) return OutputService::error("短信验证码错误！");
        } else {
            if(empty($request->username)) return OutputService::error("请输入登录账号！");
            if(empty($request->password)) return OutputService::error("请输入登录密码！");
            $phone = str_replace(" ","",$request->username);
        }
        // 校验是否存在
        $users = Users::getAdminByUsername($phone);
        $siteConfig = Config::get("adminlogin.login");
        if (empty($users)) {
            $keyword = urldecode($request->keyword);
            if (strpos($keyword, '%E') !== false) {
                $keyword = urldecode($keyword);
            } 
            if ($request->login_type == "password") return OutputService::error("账号或密码错误!");
            $keyword  = mb_strlen($keyword) > 35 ? mb_substr($keyword, 0,35) : urldecode($keyword);
            $ncode  = mb_strlen($request->ncode) > 35 ? mb_substr($request->ncode, 0,35) : $request->ncode;
            if (!empty($request->unionid)) {
                // 先关注再绑定的手机号
                // 获取公众号注册的用户ID
                $openidUsers = Users::getUsersByUnionid($request->unionid);
                // 如果公众号不为空
                if (!empty($openidUsers)) {
                    if(!empty($openidUsers->username)) return OutputService::error("该手机号已被绑定，请刷新页面后直接用手机号验证码登录！",[],1500);
                    Users::phoneBind($openidUsers->id,$phone,'');
                    $users_id = $openidUsers->id;
                    CalltaskService::phonePush($phone);
                } else {
                    if(empty($request->code)){
                        try {
                            $users_id = Users::creatUsersByUnionid($request->unionid,$phone,$ncode,$keyword,$request->device); 
                        } catch (Exception $e) {
                            $users_id = Users::creatUsersByUnionid($request->unionid,$phone,$ncode,'',$request->device);
                        }
                    }else{
                        $users_invitation_id = CommonService::aesDncrypt(urldecode($request->code));
                        if(empty($users_invitation_id)){

                        }else{
                            Usersinvitations::addUsersInvitation($userInfo->id,$users_invitation_id);
                        }
                    }
                    //新注册用户，加入拨打电话任务
                    CalltaskService::phonePush($phone);
                }
                $unionid = $request->unionid;
            } else {
                // 先使用验证码注册
                if ($siteConfig['login_auth'] == "fpm" && empty($openid) && $request->device == 1){
                    return OutputService::success("请绑定关注公众号!",[],2000);
                }else{
                    if(empty($request->code)){
                        try {
                            $users_id = Users::creatUsersByUnionid('',$phone,$ncode,$keyword,$request->device);
                        } catch (Exception $e) {
                            $users_id = Users::creatUsersByUnionid('',$phone,$ncode,'',$request->device);
                        }
                    }else{
                        $users_invitation_id = CommonService::aesDncrypt(urldecode($request->code));
                        if(empty($users_invitation_id)){
                            try {
                                $users_id = Users::creatUsersByUnionid('',$phone,$request->code,$keyword,$request->device);
                            } catch (Exception $e) {
                                $users_id = Users::creatUsersByUnionid('',$phone,$request->code,'',$request->device);
                            }
                        }else{
                            $users_id = Users::creatUsersByUnionid('',$phone,$ncode,$keyword,$request->device);
                            Usersinvitations::addUsersInvitation($users_id,$users_invitation_id);
                        }
                    }
                    Auth::loginUsingId($users_id,true);
                    //新注册用户，加入拨打电话任务
                    CalltaskService::phonePush($phone);
                    return OutputService::success("SUCCESS");
                }
                $unionid = "";
            }
        } else {
            $users_id = $users->id;
            if ($request->login_type == "password") {
                if (!password_verify($request->password, $users->password)) return OutputService::error("账号或密码错误!");
            }
            if(!empty($request->unionid)){
                $openidUsers = Users::getUsersByUnionid($request->unionid);
                // 如果公众号不为空
                if (empty($openidUsers)) {
                    if(!empty($users->unionid)) return OutputService::error("该手机号已被绑定，请刷新页面后直接用手机号验证码登录1！",[],1500);
                    // 绑定当前账户的手机号
                    Users::bindUnionidByUserName($request->unionid,$phone);
                } else {
                    // 先用手机注册的然后又绑定
                    if ($users->id != $openidUsers->id) {
                        if (empty($openidUsers->username)) {
                            // 更新老的账号的账号的绑定
                            Users::updateUserOpenId($users->id,$openidUsers->wechat_openid,$request->unionid);
                            Users::deleteUser($openidUsers->id);
                        } else {
                            return OutputService::error("该手机号已被绑定，请刷新页面后直接用手机号验证码登录！",[],1500);
                        }
                    }
                }
            }
            // 账号已被禁用
            if ($users->disable == 2) return OutputService::error("对不起，此账号已被禁用！");
            $unionid = empty($request->unionid) ? $users->unionid : $request->unionid;
        }

        // 判断是否需要关注公众号
        if ($siteConfig['login_auth'] == "fpm" && empty($unionid) && $request->device == 1) return OutputService::success("请绑定关注公众号!",[],2000);
        // 验证成功，加入auth
        Auth::loginUsingId($users_id,true);
        if (empty($users)) {
            $jump = '/admin/links_lists/links_lists_add';
        } else {
            if(time() - strtotime($users->created_at) > 259200){
                $jump = '/admin/links_lists/lists';
            }else{
                $jump = '/admin/links_lists/links_lists_add';
            }
        }
        return OutputService::success("SUCCESS",['jump'=>$jump]);
    }

    public function wechatLogin(Request $request)
    {
        $timestamp = $request->timestamp;
        $unionid = $request->unionid;
        $token = $request->token;
        $username = empty($request->phone) ? "" : $request->phone;
        if (empty($request->timestamp) || empty($request->unionid) || empty($request->token)) return OutputService::error("接口异常,请稍后重试！");
        if (md5($timestamp."S".$unionid."A") != $token) return OutputService::error("接口异常,请稍后重试！");
        $users = Users::getUsersByUnionid($unionid);
        $siteConfig = Config::get("adminlogin.login");
        //扫码登录，已经创建了用户
        if(!empty($username)){
           $userbyphone = Users::getAdminByUsername($username);
            if(empty($userbyphone)){
                if(!empty($users->username)) return OutputService::error("扫码微信号已被其他手机号绑定，请刷新页面后直接扫码登录",[],1500);
                Users::bindUserNameByOpenid($openid,$username);
            }else{
                if($userbyphone->id != $users->id) return OutputService::error("扫码微信号已被其他手机号绑定，请刷新页面后直接扫码登录",[],1500);
            } 
        }
        $users_id = $users->id;
        $username = empty($username) ? $users->username : $username;
        // 判断是否需要绑定手机号
        if ($siteConfig['login_auth'] == "fpm" && empty($username)) return OutputService::success("请绑定手机号!",[],2000);
        Auth::loginUsingId($users_id);
        if(time() - strtotime($users->created_at) > 259200){
            $jump = '/admin/links_lists/lists';
        }else{
            $jump = '/admin/links_lists/links_lists_add';
        }
        return OutputService::success("SUCCESS",['jump'=>$jump]);
    }

    public function mpLogin(Request $request)
    {
        try {
            $mpLoginInfo = WechatOpenidService::getOpenid();
        } catch (Exception $e) {
            $mpLoginInfo = ["openid"=>"","access_token" => ""];
        }
        if (!isset($mpLoginInfo["openid"]) || empty($mpLoginInfo["openid"])) return view('links.notice',["msg"=>"公众号登录失败,请使用电脑登录!"]);
        $userInfo = WechatOpenidService::officialUsersInfo($mpLoginInfo["access_token"],$mpLoginInfo["openid"]);
        $users = Users::getUsersByOpenid($mpLoginInfo["openid"]);
        if (empty($users)) {
            $users_id = Users::creatUsersByOpenid($mpLoginInfo["openid"],$userInfo["headimgurl"],$userInfo["nickname"],$userInfo["sex"]);
        } else {
            $users_id = $users->id;
        }
        Auth::loginUsingId($users_id);
        return redirect("/admin/users/users_center");

    }

    public function policyDetial(Request $request,$policy)
    {
        $loginPolicy = config("adminlogin.policy");
        return view("admin.logins.policy_".$policy,["loginPolicy"=>$loginPolicy]);
    }

    public function uploadIe(Request $request)
    {
        Log::info('ie_visit==================_start');
        Log::info($_SERVER['HTTP_USER_AGENT']);
        Log::info('ie_visit==================_end');
        return OutputService::success("SUCCESS");
    }




    public function safeTip(Request $request)
    {
        $type = empty($request->type) ? 1 : $request->type;
        $hturl = [
            [],
            ['url'=>'https://admin.tgzhb.cn','name'=>'您即将跳转进入摩尔营销通','describe'=>'跳转摩尔营销通后使用过程如有问题联系摩尔营销通客服！','mp'=>2],
            ['url'=>'https://bab.moreqifu.cn','name'=>'即将跳转到天天外链','describe'=>'跳转天天外链后使用过程如有问题联系天天外链客服！','mp'=>1],
            ['url'=>'https://duoyue.moreqifu.cn','name'=>'即将跳转到多悦数据','describe'=>'多悦数据可帮助企业实现数据回传/落地页制作/腾讯官方小程序跳转等，且<font color="#2972fa">天天外链与多悦数据可共用会员</font>(具体联系客服)。','mp'=>2]
        ];
        $code = empty(Auth::user()->code) ? 'wlht' : Auth::user()->code;
        $keyword = empty(Auth::user()->keyword) ? '天天外链一键登录' : Auth::user()->keyword;
        $client = new Client();
        $response = $client->request("POST", $hturl[$type]['url']."/api/version/1/login/get_login_token?username=".Auth::user()->username."&openid=".Auth::user()->openid."&open_userid=&code=".$code."&keyword=".$keyword."&mp=1");
        $results = json_decode($response->getBody());
        if($results->status == 'error') return redirect($hturl[$type]['url'].'/admin/common/login/login');
        $data = $results->data;
        $id = $data->token;
        $key = time();
        $sign = md5('zhbk'.$key.'kbhz');
        $target = $hturl[$type]['url'].'/admin/common/login/login_use_token?key='.$key.'&sign='.$sign.'&id='.$id;
        return view('admin.logins.safe_tip',['target'=>$target,'name'=>$hturl[$type]['name'],'describe'=>$hturl[$type]['describe']]);
    }

    public function LoginUseToken(Request $request){
        if(Auth::check()) return redirect('/admin/links_lists/links_lists_add');
        if (empty($request->key) || empty($request->sign)) return redirect('/admin/common/login/login');
        if (abs(time() - $request->key) >= 300) return redirect('/admin/common/login/login');
        if($request->sign != md5('zhbk'.$request->key.'kbhz')) return redirect('/admin/common/login/login');
        Auth::loginUsingId(decrypt($request->id));
        return redirect('/admin/links_lists/links_lists_add');
    }

    public function ttwkLogin(Request $request)
    {
        $suite_id = empty($request->suite_id) ? "wwdbc75e4a6e50a684" : $request->suite_id;
        if (empty($request->suite_id)) {
            $config = Config::get("weixin.work.wwdbc75e4a6e50a684");
            $redirect_uri = urlencode("https://bab.moreqifu.cn/admin/common/ttwk_login_back");
        } else {
            $config = Config::get("weixin.work.".$request->suite_id);
            $redirect_uri = urlencode("https://bab.moreqifu.cn/admin/common/ttwk_login_back");
        }
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$config["suite_id"]."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_base&state=".$suite_id."#wechat_redirect";
        return redirect()->away($url);
    }

    public function ttwkLoginBack(Request $request)
    {
        $suite_id = empty($request->state) ? "wwdbc75e4a6e50a684" : $request->state;
        $usersInfo = WorkcustomService::getUserInfo3rd($suite_id,$request->code);
        if ($usersInfo["errcode"] != 0) return view("links.error_notice",["msg"=>$usersInfo["errmsg"]]);
        $users = Users::getUsersByOpenUserid($usersInfo["open_userid"]);
        if (empty($users)) {
            $users_id = Users::creatUsersByWork($usersInfo["open_userid"],$usersInfo["UserId"],"ttwk","http://p.qpic.cn/pic_wework/1415612393/74723564f7cc73a584ad90fdffe98eb1639e6b1e9557edae/0");
        } else {
            $users_id = $users->id;
        }

        // 首先确定登录成功
        Auth::loginUsingId($users_id);
        return redirect("https://bab.moreqifu.cn/admin/wxkf/wxkf_list");
    }
}
